package com.hjq.demo.ui.activity;

import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.demo.R;
import com.hjq.demo.action.StatusAction;
import com.hjq.demo.app.AppActivity;
import com.hjq.demo.http.api.DeleteShipmentApi;
import com.hjq.demo.http.api.ShipmentListApi;
import com.hjq.demo.http.api.UserListApi;
import com.hjq.demo.http.model.HttpData;
import com.hjq.demo.ui.adapter.ShipmentRecordAdapter;
import com.hjq.demo.ui.dialog.DateDialog;
import com.hjq.demo.ui.dialog.MenuDialog;
import com.hjq.demo.ui.dialog.MessageDialog;
import com.hjq.demo.ui.fragment.HomeFragment;
import com.hjq.demo.widget.StatusLayout;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.shape.view.ShapeTextView;
import com.hjq.widget.layout.WrapRecyclerView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class SearchShipmentRecordActivity extends AppActivity implements OnRefreshLoadMoreListener,
        BaseAdapter.OnItemClickListener,
        BaseAdapter.OnItemLongClickListener , StatusAction {
    private StatusLayout mStatusLayout;
    private ShapeTextView selectCustomerName;
    private ShapeTextView selectStartTime;
    private ShapeTextView selectEndTime;
    //刷新
    private SmartRefreshLayout mRefreshLayout;
    //列表
    private WrapRecyclerView mRecyclerView;
    private int pageSize = 10;
    private int pageNum = 1;
    private RelativeLayout llSearchSelect;
    private ShipmentRecordAdapter mAdapter;
    /**
     * 总数量
     */
    private int totalNumber;
    private SmartRefreshLayout rlShipmenEcordRefresh;
    private WrapRecyclerView rvShipmenEcordList;
    private LinearLayout llSelectAllView;
    private TextView tvSelectNum;
    private Button btnDelete;
    private TextView selectAll;
    private AppCompatEditText selectTradeName;
    private AppCompatButton btnSearch;
    private AppCompatButton btnClean;

    private int Type = 0;
    @Override
    protected int getLayoutId() {
        return R.layout.search_shipmen_ecord_activity;
    }


    @Override
    protected void initView() {
        selectCustomerName = (ShapeTextView) findViewById(R.id.select_customer_name);
        selectStartTime = (ShapeTextView) findViewById(R.id.select_start_time);
        selectEndTime = (ShapeTextView) findViewById(R.id.select_end_time);
        mRefreshLayout = findViewById(R.id.rl_shipmen_ecord_refresh);
        mRecyclerView = findViewById(R.id.rv_shipmen_ecord_list);
        selectTradeName = (AppCompatEditText) findViewById(R.id.select_trade_name);
        tvSelectNum = (TextView) findViewById(R.id.tv_select_num);
        btnDelete = (Button) findViewById(R.id.btn_delete);
        selectAll = (TextView) findViewById(R.id.select_all);
        llSelectAllView = (LinearLayout) findViewById(R.id.ll_select_all_view);
        llSearchSelect = (RelativeLayout) findViewById(R.id.ll_search_select);
        mAdapter = new ShipmentRecordAdapter(getActivity());
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemLongClickListener(this);
        mRecyclerView.setAdapter(mAdapter);
        mStatusLayout = findViewById(R.id.hl_status_hint);

        btnClean = (AppCompatButton) findViewById(R.id.btn_clean);




        btnSearch = (AppCompatButton) findViewById(R.id.btn_search);


//        TextView headerView = mRecyclerView.addHeaderView(R.layout.picker_item);
//        headerView.setText("我是头部");
//        headerView.setOnClickListener(v -> toast("点击了头部"));
//
//        TextView footerView = mRecyclerView.addFooterView(R.layout.picker_item);
//        footerView.setText("我是尾部");
//        footerView.setOnClickListener(v -> toast("点击了尾部"));

        mRefreshLayout.setOnRefreshLoadMoreListener(this);
        setOnClickListener(selectCustomerName,
                selectStartTime,
                selectEndTime,
                selectAll, btnDelete,btnSearch,btnClean);
    }

    @Override
    protected void initData() {
        analogData();
        mAdapter.setOnListener(new ShipmentRecordAdapter.OnListener() {
            @Override
            public void acbIsSelectListener() {
                isSelectNum();
            }
        });

    }

    @Override
    public void onClick(View view) {

        if (view == selectCustomerName) {
            CustomerNameData();
        }else if (view == btnClean) {
            // 消息对话框
            new MessageDialog.Builder(getActivity())
                    // 标题可以不用填写
                    .setTitle("清空选择筛选记录")
                    // 内容必须要填写
                    .setMessage("确定清空选择筛选记录?")
                    // 确定按钮文本
                    .setConfirm(getString(R.string.common_confirm))
                    // 设置 null 表示不显示取消按钮
                    .setCancel(getString(R.string.common_cancel))
                    // 设置点击按钮后不关闭对话框
                    //.setAutoDismiss(false)
                    .setListener(new MessageDialog.OnListener() {

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            selectTradeName.setText("");
                            selectCustomerName.setText("");
                            selectStartTime.setText("");
                            selectEndTime.setText("");
                            pageNum = 1;
                            analogData();
                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                            toast("取消删除");
                        }
                    })
                    .show();
        }else if (view == btnSearch) {
            pageNum = 1;
            analogData();
        } else if (view == btnDelete) {
            if (Integer.parseInt(tvSelectNum.getText().toString()) == 0) {
                toast("请选择要删除的出货记录不能为空");
                return;
            }
            // 消息对话框
            new MessageDialog.Builder(getActivity())
                    // 标题可以不用填写
                    .setTitle("删除")
                    // 内容必须要填写
                    .setMessage("是否确认删除本次选择的出货记录?")
                    // 确定按钮文本
                    .setConfirm(getString(R.string.common_confirm))
                    // 设置 null 表示不显示取消按钮
                    .setCancel(getString(R.string.common_cancel))
                    // 设置点击按钮后不关闭对话框
                    //.setAutoDismiss(false)
                    .setListener(new MessageDialog.OnListener() {

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            StringBuilder ids = new StringBuilder();
                            for (int i = 0; i < mAdapter.getData().size(); i++) {
                                if (mAdapter.getData().get(i).getSelect() == null) {
                                    mAdapter.getData().get(i).setSelect(false);
                                }
                                if (mAdapter.getData().get(i).getSelect()) {
                                    ids.append(mAdapter.getData().get(i).getId() + ",");
                                }
                                if (mAdapter.getData().size() - 1 == i) {
                                    DeleteShipmentHttp(ids.toString());
                                }
                            }

                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                            toast("取消删除");
                        }
                    })
                    .show();
        } else if (view == selectStartTime) {
            // 日期选择对话框
            new DateDialog.Builder(this)
                    .setTitle(getString(R.string.date_title))
                    // 确定按钮文本
                    .setConfirm(getString(R.string.common_confirm))
                    // 设置 null 表示不显示取消按钮
                    .setCancel(getString(R.string.common_cancel))
                    // 设置日期
                    //.setDate("2018-12-31")
                    //.setDate("20181231")
                    //.setDate(1546263036137)
                    // 设置年份
                    //.setYear(2018)
                    // 设置月份
                    //.setMonth(2)
                    // 设置天数
                    //.setDay(20)
                    // 不选择天数
                    //.setIgnoreDay()
                    .setListener(new DateDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, int year, int month, int day) {
                            toast(year + getString(R.string.common_year) + month + getString(R.string.common_month) + day + getString(R.string.common_day));

                            // 如果不指定时分秒则默认为现在的时间
                            Calendar calendar = Calendar.getInstance();
                            calendar.set(Calendar.YEAR, year);
                            // 月份从零开始，所以需要减 1
                            calendar.set(Calendar.MONTH, month - 1);
                            calendar.set(Calendar.DAY_OF_MONTH, day);
                            //toast(new SimpleDateFormat("yyyy年MM月dd日 kk:mm:ss").format(calendar.getTime()));
                            selectStartTime.setText(year + "-" + month + "-" + day);

                        }

                        @Override
                        public void onCancel(BaseDialog dialog) {
                            toast("取消了");
                        }
                    })
                    .show();
        } else if (view == selectEndTime) {
            // 日期选择对话框
            new DateDialog.Builder(this)
                    .setTitle(getString(R.string.date_title))
                    // 确定按钮文本
                    .setConfirm(getString(R.string.common_confirm))
                    // 设置 null 表示不显示取消按钮
                    .setCancel(getString(R.string.common_cancel))
                    // 设置日期
                    //.setDate("2018-12-31")
                    //.setDate("20181231")
                    //.setDate(1546263036137)
                    // 设置年份
                    //.setYear(2018)
                    // 设置月份
                    //.setMonth(2)
                    // 设置天数
                    //.setDay(20)
                    // 不选择天数
                    //.setIgnoreDay()
                    .setListener(new DateDialog.OnListener() {
                        @Override
                        public void onSelected(BaseDialog dialog, int year, int month, int day) {
                            toast(year + getString(R.string.common_year) + month + getString(R.string.common_month) + day + getString(R.string.common_day));

                            // 如果不指定时分秒则默认为现在的时间
                            Calendar calendar = Calendar.getInstance();
                            calendar.set(Calendar.YEAR, year);
                            // 月份从零开始，所以需要减 1
                            calendar.set(Calendar.MONTH, month - 1);
                            calendar.set(Calendar.DAY_OF_MONTH, day);
                            //toast(new SimpleDateFormat("yyyy年MM月dd日 kk:mm:ss").format(calendar.getTime()));
                            selectEndTime.setText(year + "-" + month + "-" + day);
                        }
                        @Override
                        public void onCancel(BaseDialog dialog) {
                            toast("取消了");
                        }
                    })
                    .show();
        }  else if (view == selectAll) {
            mAdapter.ShipmentRecordAdapterIsAllSelect(mAdapter.isAllSelect);
            if (!mAdapter.isAllSelect) {
                selectAll.setText("全选");
            } else {
                selectAll.setText("取消全选");
            }
            isSelectNum();
        }
    }
    private void DeleteShipmentHttp(String ids) {
        ids = ids.substring(0, ids.length() - 1);
        EasyHttp.post(this)
                .api(new DeleteShipmentApi()
                        .setIds(ids)
                )
                .request(new HttpCallback<HttpData<DeleteShipmentApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<DeleteShipmentApi.Bean> data) {
                        //删除成功
                        toast("删除成功");
                        onIsShowBottom(false);
                        pageNum = 1;
                        analogData();
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                        toast(R.string.common_edit_error);
                    }
                });

    }

    //客户名称data
    private void CustomerNameData() {
        EasyHttp.get(this)
                .api(new UserListApi().setPageSize("100")
                        .setPageNum("1"))
                .request(new HttpCallback<HttpData<UserListApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<UserListApi.Bean> data) {
                        int dataNameSize = data.getData().getRows().size();
                        //居中选择框
                        List<String> dataName = new ArrayList<>();
                        for (int i = 0; i < dataNameSize; i++) {
                            dataName.add(data.getData().getRows().get(i).getUsername());
                        }
                        /**
                         * 模拟数据
                         */
                        new MenuDialog.Builder(getContext())
                                .setGravity(Gravity.CENTER)
                                // 设置 null 表示不显示取消按钮
                                //.setCancel(null)
                                // 设置点击按钮后不关闭对话框
                                //.setAutoDismiss(false)
                                .setList(dataName)
                                .setListener(new MenuDialog.OnListener<String>() {
                                    @Override
                                    public void onSelected(BaseDialog dialog, int position, String string) {
                                        selectCustomerName.setText(string);
                                    }

                                    @Override
                                    public void onCancel(BaseDialog dialog) {
                                        toast("取消了");
                                    }
                                })
                                .show();
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });

    }

    /**
     * 模拟数据
     */
    private void analogData() {
        ShipmentListApi type =   new ShipmentListApi();
        //判断商品名称是否为空
        if (!selectTradeName.getText().toString().isEmpty()){
            type = type.setTradeName(selectTradeName.getText().toString());
        }
        //判断客户名称是否为空
        if (!selectCustomerName.getText().toString().isEmpty()){
            type = type.setUserId(selectCustomerName.getText().toString());
        }
        if (!selectStartTime.getText().toString().isEmpty() &&  !selectEndTime.getText().toString().isEmpty()){
            type.setBeginTime(selectStartTime.getText().toString()).setEndTime(selectEndTime.getText().toString());
        }
        type.setPageSize(pageSize+"").setPageNum (pageNum+"");
        EasyHttp.get(this)
                .api(type)
                .request(new HttpCallback<HttpData<ShipmentListApi.Bean>>(this) {

                    @Override
                    public void onSucceed(HttpData<ShipmentListApi.Bean> data) {
                        totalNumber = data.getData().getTotal();
                        if (pageNum == 1) {
                            mAdapter.clearData();
                            mAdapter.setData(data.getData().getRows());
                        } else {
                            mAdapter.addData(data.getData().getRows());
                        }
                        if (totalNumber == 0){
                            toast("没有查询到数据,请换其他查询条件.");
                            showEmpty();
                        }
                        if (mAdapter.getData().isEmpty() || mAdapter.getData() == null){
                            showEmpty();
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
    }

    /**
     * {@link BaseAdapter.OnItemClickListener}
     *
     * @param recyclerView RecyclerView对象
     * @param itemView     被点击的条目对象
     * @param position     被点击的条目位置
     */
    @Override
    public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
        if (mAdapter.isSelect) {

        } else {
            Type = 1;
            AddShipmentRecordActivity.start(getContext(), "3", mAdapter.getItem(position));
        }

    }

    /**
     * {@link BaseAdapter.OnItemLongClickListener}
     *
     * @param recyclerView RecyclerView对象
     * @param itemView     被点击的条目对象
     * @param position     被点击的条目位置
     * @return
     */
    @Override
    public boolean onItemLongClick(RecyclerView recyclerView, View itemView, int position) {
        onIsShowBottom(true);
        return false;
    }

    public void onIsShowBottom(Boolean isShow) {
        if (isShow) {
            btnClean.setVisibility(View.GONE);
            btnSearch.setVisibility(View.GONE);
            llSearchSelect.setVisibility(View.GONE);
            llSelectAllView.setVisibility(View.VISIBLE);
            mAdapter.ShipmentRecordAdapterIsSelect(true);
        } else {
            btnClean.setVisibility(View.VISIBLE);
            btnSearch.setVisibility(View.VISIBLE);
            llSearchSelect.setVisibility(View.VISIBLE);
            llSelectAllView.setVisibility(View.GONE);
            mAdapter.ShipmentRecordAdapterIsSelect(false);
        }

    }

    /**
     * {@link OnRefreshLoadMoreListener}
     */

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        postDelayed(() -> {
            mAdapter.clearData();
            analogData();
            mRefreshLayout.finishRefresh();
        }, 1000);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        pageNum = pageNum + 1;
        postDelayed(() -> {
            analogData();
            mRefreshLayout.finishLoadMore();
            mAdapter.setLastPage(mAdapter.getCount() >= 100);
            mRefreshLayout.setNoMoreData(isLastPage());
            isSelectNum();
        }, 1000);

    }


    /**
     * 判断是否是最后一页
     */
    public boolean isLastPage() {
        return Math.ceil((float) totalNumber / pageSize) <= pageNum;
    }

    public void isSelectNum() {
        int a = 0;
        for (int i = 0; i < mAdapter.getData().size(); i++) {
            if (mAdapter.getData().get(i).getSelect() == null) {
                mAdapter.getData().get(i).setSelect(false);
            }
            if (mAdapter.getData().get(i).getSelect()) {
                a++;
            }
            if (mAdapter.getData().size() - 1 == i) {
                tvSelectNum.setText(a + "");
                if (a == mAdapter.getData().size()) {
                    selectAll.setText("取消全选");
                } else {
                    selectAll.setText("全选");
                }
            }
        }


    }

    @Override
    public StatusLayout getStatusLayout() {
        return mStatusLayout;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Type == 1){
            onRefresh(mRefreshLayout);
        }
    }
}
